from django.shortcuts import render
from rest_framework.views import APIView
from .models import User,Address
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from .serializers import RegisterCreateSerializer,UserInfoSerializer,EmailSerializer,AddressSerializer
from rest_framework.generics import RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import UpdateAPIView
from rest_framework import status
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin,RetrieveModelMixin,CreateModelMixin,DestroyModelMixin,UpdateModelMixin
from rest_framework.decorators import action
from .serializers import AddressTitleSerializer

# Create your views here.

class RegisterUsernameCountAPIView(APIView):

    """
    获取用户名个数
    GET: /users/usernames/(?P<username>\w{5,20})/count/
    """

    def get(self,request,username):
        """
        根据用户名获取个数
        """

        count = User.objects.filter(username=username).count()

        context = {
            'username':username,
            'count':count
        }

        return Response(context)

class RegisterPhoneCountAPIView(APIView):
    """
    查询手机号的个数
    GET: /users/phones/(?P<mobile>1[345789]\d{9})/count/
    """
    def get(self,request,mobile):

        #通过模型查询获取手机号个数
        count = User.objects.filter(mobile=mobile).count()
        #组织数据
        context = {
            'count':count,
            'phone':mobile
        }

        return Response(context)

class RegisterCreateView(CreateAPIView):

    """
    实现用户注册
    POST /users/

    思路：
        创建序列化器，进行数据校验
    """

    serializer_class = RegisterCreateSerializer



class UserInfoView(RetrieveAPIView):
    """
    GET  /users/infos/
    必须是登录用户
    """
    permission_classes = [IsAuthenticated]

    serializer_class = UserInfoSerializer

    def get_object(self):
        return self.request.user


class EmailView(UpdateAPIView):

    """
    发送激活邮件
     PUT /users/emails/
    """

    permission_classes = [IsAuthenticated]

    serializer_class = EmailSerializer

    def get_object(self):

        return self.request.user


class VerificationEmailView(APIView):

    """
    验证激活邮箱
    GET /users/emails/verification/?token=xxxx

    思路：
    获取token
    判断token是否为None
    校验获取用户信息
    修改用户状态

    """

    def get(self,request):
        # 获取token
        token = request.query_params.get('token')
        # 判断token是否为None
        if token is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 校验获取用户信息
        user = User.check_active_mail_token(token)
        if user is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 修改用户状态
        user.email_active=True
        user.save()

        return Response({'message':'ok'})


class AddressViewSet(CreateModelMixin,ListModelMixin,DestroyModelMixin,UpdateModelMixin,GenericViewSet):

    """
    用户地址新增与修改
    必须为登录页面

    list GET: /users/addresses/
    create POST: /users/addresses/
    destroy DELETE: /users/addresses/
    action PUT: /users/addresses/pk/status/
    action PUT: /users/addresses/pk/title/
    """

    permission_classes = [IsAuthenticated]

    serializer_class = AddressSerializer

    def get_queryset(self):

        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        count = request.user.addresses.count()
        if count >= 20:
            return Response({'message': '保存地址数量已经达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        """
        获取用户地址列表
        """
        # 获取所有地址
        queryset = self.get_queryset()
        # 创建序列化器
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        # 响应
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)



